const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')
const koaBody = require('koa-body')
const path = require('path')
const koajwt = require('koa-jwt')

const index = require('./routes/index')
const users = require('./routes/user')
const article = require('./routes/article')
const comment = require('./routes/comment')
const fans = require('./routes/fans')
const checkDirExist = require('./utils/checkDirExist')
const getUploadDirName = require('./utils/getUploadDirName')
const getUploadFileExt = require('./utils/getUploadFileExt')

// error handler
onerror(app)

// middlewaresvar
// 处理跨域
app.use(cors())

app.use(koaBody({
  // 启用文件传输
  multipart: true,
  formidable: {
    // 上传目录
    uploadDir: path.join(__dirname, '/public/uploads'),
    // 保留扩展名
    keepExtensions: true,
    // 限制文件大小
    maxFieldsSize: 2 * 1024 * 1024,
    onFileBegin: (name, file) => {
      // console.log(file);
      // 获取文件后缀
      const ext = getUploadFileExt(file.name);
      // 最终要保存到的文件夹目录
      const dir = path.join(__dirname, `public/uploads/${getUploadDirName()}`);
      // 检查文件夹是否存在如果不存在则新建文件夹
      checkDirExist(dir);
      // 重新覆盖 file.path 属性
      file.path = `${dir}/${path.basename(file.path)}`;
    },
    onError: (err) => {
      console.log(err);
    }

  }
}))

// token认证机制
app.use(koajwt({
  secret: 'jianshu-server-jwt'
}).unless({
  path: [/^\/user\/login/, /^\/user\/register/, /^\/uploads/]
}))

const {
  mongoose
} = require('./db/index')

app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(article.routes(), article.allowedMethods())
app.use(comment.routes(), comment.allowedMethods())
app.use(fans.routes(), fans.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app